import unittest

from tinydb.storage.bplus_tree import *

class TestBPlusTree(unittest.TestCase):
    def test_bplustree(self):
        tree = BPlusTree()

        for i in range(0, 100):
            tree.insert(i, i)

        for i in range(0, 100):
            self.assertEqual(tree.find(i), [i])

        tree.insert(1, 100)
        tree.insert(2, 200)
        tree.insert(3, 3)
        
        self.assertEqual(tree.find(1),[1, 100])
        self.assertEqual(tree.find(2),[2, 200])
        self.assertEqual(tree.find(3),[3, 3])

        self.assertEqual(tree.find_range(0, 4), [1, 100, 2, 200, 3, 3])

        self.assertEqual(tree.find_range(0, 4, return_keys=True), [1, 1, 2, 2, 3, 3])

        self.assertEqual(len(tree.find_range(start=0)), 102)
        excepted = list(range(1, 100))
        excepted.insert(1,100)
        excepted.insert(3,200)
        excepted.insert(4,3)
        self.assertEqual(tree.find_range(start=0), excepted)
        self.assertEqual(len(tree.find_range()), 103)

        tree.delete(1)
        self.assertEqual(tree.find(1), [])

        tree.delete(3)
        self.assertEqual(tree.find(3), [])

        for i in range(0, 100):
            tree.insert(3, i) # 往key为3的节点中插入100个元素

        self.assertEqual(len(tree.find(3)), 100)
        result = tree.find(3)
        result.sort()
        self.assertEqual(result, list(range(0, 100)))

if __name__ == '__main__':
    unittest.main()
